package ui;

 
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import results.ClusterVector;
import counter.DocumentNoun;
 
/**
 * User interface to load sequence and blosum62 files.
 * Also there exist a button to run algorithm and 
 * another button to save output.
 * JFrame is used.
 * 
 * CMPE530
 * Project
 * Ali Erkan
 * 2010800024
 *   
 */

public class MainWindow extends JPanel
                             implements Serializable, ActionListener {
    static private final String newline = "\n";
    //Buttons 
    JButton openFirstButton, openSecondButton, openThirdButton, processButton, printButton;
    JTextArea log;
    JFileChooser fc;
    JFileChooser fw;
    DocumentNoun docNoun;
 
    public MainWindow() {
        super(new BorderLayout());
 
        //Create the log first, because the action listeners
        //need to refer to it.
        log = new JTextArea(5,20);
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(log);
 
        //Create a file chooser
        fc = new JFileChooser();
        fw = new JFileChooser();
 
        //Uncomment one of the following lines to try a different
        //file selection mode.  The first allows just directories
        //to be selected (and, at least in the Java look and feel,
        //shown).  The second allows both files and directories
        //to be selected.  If you leave these lines commented out,
        //then the default mode (FILES_ONLY) will be used.
        //
        //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
 
        //Create the open button.  We use the image from the JLF
        //Graphics Repository (but we extracted it from the jar).
        openFirstButton = new JButton("Open a First File", null);
                                 //createImageIcon("images/Open16.gif"));
        openFirstButton.addActionListener(this);
        
        //Create the print button.  We use the image from the JLF
        //Graphics Repository (but we extracted it from the jar).
        printButton = new JButton("Print Results", null);
                                 //createImageIcon("images/Save16.gif"));
        printButton.addActionListener(this);
 
        //For layout purposes, put the buttons in a separate panel
        JPanel buttonPanel = new JPanel(); //use FlowLayout
        buttonPanel.add(openFirstButton);  //To load first sequence
        buttonPanel.add(printButton);      //To store output
 
        //Add the buttons and the log to this panel.
        add(buttonPanel, BorderLayout.PAGE_START);
        add(logScrollPane, BorderLayout.CENTER);
    }
 
    /* (non-Javadoc)
     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     */
    public void actionPerformed(ActionEvent e) {
        DocumentNoun docNoun = new DocumentNoun();
    	//Handle first open button action.
        if (e.getSource() == openFirstButton) {
        	fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = fc.showOpenDialog(MainWindow.this);
 
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File dir = fc.getSelectedFile();
                fw.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                int returnValOut = fw.showOpenDialog(MainWindow.this);
                if (returnValOut == JFileChooser.APPROVE_OPTION) {
                	File outFile = fw.getSelectedFile();
                
	                try {
	                	docNoun.getNouns(dir);
	                	docNoun.createMatrix();
	                	docNoun.writeFile(outFile);
	                } catch(Exception ex) {
	                	log.append("File couldn't be read: " + ex.getMessage() + "." + newline);
	                }
	                
	                log.append("File was read from: " + dir.getName() + "." + newline);
                }
            } else {
                log.append("Open command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
        
        //Handle write button action.
        } else if (e.getSource() == printButton) {
        	fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        	fw.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int returnValIn = fc.showSaveDialog(MainWindow.this);
            if (returnValIn == JFileChooser.APPROVE_OPTION) {
            	fw.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int returnValOut = fw.showSaveDialog(MainWindow.this);
                if (returnValOut == JFileChooser.APPROVE_OPTION) {
	            	//Store output into a file.
	                File inFile = fc.getSelectedFile();
	                File outFile = fw.getSelectedFile();
	                
	                log.append("Saving: " + inFile.getName() + "." + newline);
	                log.append("Saving: " + outFile.getName() + "." + newline);
	                ClusterVector cVector = new ClusterVector();
	                try {
		                cVector.printCenters(inFile, outFile);
	                } catch(Exception io) {
	                	log.append("File Error: " + io.getMessage() + "." + newline);
	                }
                
                }
            } else {
                log.append("Save command cancelled by user." + newline);
            }
            log.setCaretPosition(log.getDocument().getLength());
        }
    }
 
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = MainWindow.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
 
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Needleman-Wunsch Dynamic Programming Global Sequence Alignment");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        //Add content to the window.
        frame.add(new MainWindow());
 
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
 
    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE); 
                createAndShowGUI();
            }
        });
    }
}